<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    fullscreen
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    style="top:20px;height: 95%;">
    <!--底部标签-->
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="billPrintFlag && isShowPrintBtn" @click="handlePrint('采购退货出库')">三联打印预览</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">保存并审核</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">保存（Ctrl+S）</a-button>
      <!--发起多级审核-->
      <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">提交流程</a-button>
    </template>
    <!--dialog内容-->
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!--新增第一列-->
        <a-row class="form-row" :gutter="24">
          <!--发票编号-->
          <a-col :lg="5" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发票编号">
              <a-input placeholder="请输入发票编号" v-decorator.trim="[ 'invoiceNumber', validatorRules.invoiceNumber]" />
            </a-form-item>
          </a-col>
          <!--发票类型-->
          <a-col :lg="4" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发票类型">
              <a-select placeholder="请选择发票类型" v-decorator="[ 'invoiceType', validatorRules.invoiceType ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children" @change="invoiceTypeChange">
                <a-select-option v-for="(item,index) in invoiceTypeList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--报关单号-->
          <a-col :lg="5" :md="12" :sm="24" v-if="iceType===1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报关单号">
              <a-input placeholder="请输入报关单号" v-decorator.trim="[ 'reportNo' ]" />
            </a-form-item>
          </a-col>
          <!--选择客户OR供应商-->
          <a-col :lg="5" :md="12" :sm="24" v-if="iceType">
            <a-form-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="iceType===1">
              <a-select placeholder="请选择客户" v-decorator="[ 'customerSupplierId', validatorRules.customerSupplierId ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children" @change="cliOrSupChange">
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="iceType===2">
              <a-select placeholder="请选择供应商" v-decorator="[ 'customerSupplierId', validatorRules.customerSupplierId ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children" @change="cliOrSupChange">
                <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--开票日期-->
          <a-col :lg="5" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开票日期">
              <j-date v-decorator="['invoiceDate']" :show-time="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <!--单据信息Table-->
        <a-card title="单据信息" :hoverable="true" size="small">
          <a-table
                    ref="billTable"
                    size="small"
                    rowKey="id"
                    :columns="bill.columns"
                    :dataSource="bill.data"
                    :row-selection="rowSelection"
                    :pagination="false"
          >
            <span slot="numberCustomRender" slot-scope="text, record">
              <a  @click="myHandleDetail(record)">{{record.number}}</a>
            </span>
            <template slot="customRenderStatus" slot-scope="text, record">
              <template>
                <a-tag v-if="record.status === '0'" color="red">未审核</a-tag>
                <a-tag v-if="record.status === '1'" color="green">已审核</a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
        <!--详细数据Table-->
        <a-card title="商品信息" style="margin-top: 10px;" :hoverable="true" size="small">
          <j-editable-table id="billModal"
                            :ref="refKeys[0]"
                            :ice-type="iceType"
                            :loading="materialTable.loading"
                            :columns="materialTable.columns"
                            :dataSource="materialTable.dataSource"
                            :minWidth="minWidth"
                            :maxHeight="300"
                            :rowNumber="false"
                            :rowSelection="rowCanEdit"
                            :actionButton="false"
                            :dragSortAndNumber="rowCanEdit"
                            @valueChange="onValueChange"
                            @added="onAdded"
                            @deleted="onDeleted">
            <template #buttonAfter v-if="false">
              <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4" data-title="扫码录入" data-intro="此功能支持扫码枪扫描商品条码进行录入">
                <a-col v-if="scanStatus" :md="6" :sm="24">
                  <a-button @click="scanEnter" style="margin-right: 8px">扫码录入</a-button>
                </a-col>
                <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                  <a-input placeholder="请扫条码或序列号并回车" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
                </a-col>
                <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px 12px 0 0">
                  <a-button @click="stopScan" style="margin-right: 8px">收起扫码</a-button>
                </a-col>
              </a-row>
            </template>
            <template #depotBatchSet>
              <a-icon type="down" @click="handleBatchSetDepot" />
            </template>
            <template #depotAdd>
              <a-divider v-if="quickBtn.depot" style="margin: 4px 0;" />
              <div v-if="quickBtn.depot" style="padding: 4px 8px; cursor: pointer;" @click="addDepot"><a-icon type="plus" /> 新增仓库</div>
            </template>
          </j-editable-table>
        </a-card>
        <!--备注-->
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="1" placeholder="请输入备注" v-decorator="[ 'invoiceRemark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <!--其它信息-->
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="当前选中单据">
              <a-input placeholder="当前选中单据" v-decorator.trim="[ 'deliveryNoteId' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="未税金额">
              <a-input placeholder="未税金额" v-decorator.trim="[ 'subtotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="含税金额">
              <a-input placeholder="含税金额" v-decorator.trim="[ 'discountLastMoney' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结算账户">
              <a-select style="width:80%;" placeholder="请选择结算账户" v-decorator="[ 'invoiceAccount', validatorRules.invoiceAccount ]"
                        :dropdownMatchSelectWidth="false" allowClear @select="selectAccount">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="quickBtn.account" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addAccount"><a-icon type="plus" /> 新增结算账户</div>
                </div>
                <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-tooltip title="多账户明细">
                <a-button type="default" icon="folder" style="margin-left: 8px;" size="small" v-show="manyAccountBtnStatus" @click="handleManyAccount"/>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠率">
              <a-input style="width:80%;" placeholder="请输入优惠率" v-decorator.trim="[ 'discount' ]" suffix="%" @change="onChangeDiscount"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="退款优惠" v-show="false">
              <a-input placeholder="请输入付款优惠" v-decorator.trim="[ 'discountMoney' ]" @change="onChangeDiscountMoney"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="其它费用" v-show="false">
              <a-input placeholder="请输入其它费用" v-decorator.trim="[ 'otherMoney' ]" @change="onChangeOtherMoney"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="本次退款" v-show="false">
              <a-input placeholder="请输入本次退款" v-decorator.trim="[ 'changeAmount' ]" @change="onChangeChangeAmount"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="本次欠款" v-show="false">
              <a-input placeholder="请输入本次欠款" v-decorator.trim="[ 'debt' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
        </a-row>
        <!--附件-->
<!--        <a-row class="form-row" :gutter="24">-->
<!--          <a-col :lg="6" :md="12" :sm="24">-->
<!--            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="附件">-->
<!--              <j-upload v-model="fileList" bizPath="bill"></j-upload>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
      </a-form>
    </a-spin>
    <!--新增结算账户Dialog-->
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <!--选择数据Dialog-->
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <!--新增联系？-->
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <!--新增仓库-->
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <!--新增结算账户Dialog-->
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <!--批量设置仓库名称Dialog-->
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <!--应该是审批流 不过这里没有-->
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <!--三联打印Dialog-->
    <bill-print-iframe ref="modalPrint"></bill-print-iframe>
    <!-- 单据详细信息 -->
    <bill-detail ref="billDetail"></bill-detail>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import { findBillDetailByNumber } from '@/api/api'
import ManyAccountModal from '../../bill/dialog/ManyAccountModal'
import LinkBillList from '../../bill/dialog/LinkBillList'
import VendorModal from '../../system/modules/VendorModal'
import DepotModal from '../../system/modules/DepotModal'
import AccountModal from '../../system/modules/AccountModal'
import BatchSetDepot from '../../bill/dialog/BatchSetDepot'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import BillPrintIframe from '../../bill/dialog/BillPrintIframe'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '../../bill/mixins/BillModalMixin'
import { getMpListShort} from "@/utils/util"
import { getAction } from '@/api/manage'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import BillDetail from '../../bill/dialog/BillDetail.vue'
export default {
  name: "BillManageModal",
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    BillDetail,
    ManyAccountModal,
    LinkBillList,
    VendorModal,
    DepotModal,
    AccountModal,
    BatchSetDepot,
    WorkflowIframe,
    BillPrintIframe,
    JUpload,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    }
  },
  data () {
    return {
      //选择明细数据
      detailData:[],
      //单据信息
      bill:{
        columns:[
          { title: '客户', dataIndex: 'organName',width:120, ellipsis:true},
          { title: '单据编号', dataIndex: 'number',width:130,
            scopedSlots: { customRender: 'numberCustomRender' },
          },
          { title: '商品信息', dataIndex: 'materialsList',width:280, ellipsis:true,
            customRender:function (text,record,index) {
              if(text) {
                return text.replace(",","，");
              }
            }
          },
          { title: '单据日期', dataIndex: 'operTimeStr',width:145},
          { title: '操作员', dataIndex: 'userName',width:70},
          { title: '原数量', dataIndex: 'materialCount',width:60},
          { title: '已开票数量', dataIndex: 'invoiceQuantity',width:80},
          { title: '金额合计', dataIndex: 'totalPrice',width:70},
          { title: '含税合计', dataIndex: 'totalTaxLastMoney',width:70,
            customRender:function (text,record,index) {
              if(record.discountLastMoney) {
                return (record.discountMoney + record.discountLastMoney).toFixed(2);
              } else {
                return record.totalPrice;
              }
            }
          },
          { title: '状态', dataIndex: 'status', width: 70, align: "center",
            scopedSlots: { customRender: 'customRenderStatus' }
          }
        ],
        data:[],
      },
      //iceType 销售类型判断用
      iceType:undefined,
      //做票时的单据类型-采购还是销售
      invoiceTypeList:[{id:'1',supplier:"销售"},{id:'2',supplier:"采购"}],
      title:"操作",
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      visible: false,
      operTimeStr: '',
      prefixNo: 'PJ',
      fileList:[],
      rowCanEdit: true,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable', ],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: '仓库名称', key: 'depotId', width: '8%', type: FormTypes.select, placeholder: '请选择${title}', options: [],
            allowSearch:true, validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          { title: '条码', key: 'barCode', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          { title: '名称', key: 'name', width: '10%', type: FormTypes.normal },
          { title: '规格', key: 'standard', width: '5%', type: FormTypes.normal },
          { title: '型号', key: 'model', width: '6%', type: FormTypes.normal },
          { title: '颜色', key: 'color', width: '5%', type: FormTypes.normal },
          { title: '品牌', key: 'brand', width: '6%', type: FormTypes.normal },
          { title: '制造商', key: 'mfrs', width: '6%', type: FormTypes.normal },
          { title: '扩展信息', key: 'materialOther', width: '5%', type: FormTypes.normal },
          { title: '库存', key: 'stock', width: '5%', type: FormTypes.normal },
          { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
          { title: '序列号', key: 'snList', width: '12%', type: FormTypes.popupJsh, kind: 'sn', multi: true },
          { title: '批号', key: 'batchNumber', width: '7%', type: FormTypes.popupJsh, kind: 'batch', multi: false },
          { title: '有效期', key: 'expirationDate',width: '7%', type: FormTypes.input, readonly: true },
          { title: '多属性', key: 'sku', width: '9%', type: FormTypes.normal },
          { title: '原数量', key: 'preNumber', width: '5%', type: FormTypes.normal },
          { title: '已开数量', key: 'invoiceNumber', width: '6%', type: FormTypes.normal },
          { title: '开票数量', key: 'operNumber', width: '6%', type: FormTypes.inputNumber, statistics: true,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          { title: '单价', key: 'unitPrice', width: '5%', type: FormTypes.inputNumber},
          { title: '金额', key: 'allPrice', width: '5%', type: FormTypes.inputNumber, statistics: true },
          { title: '税率', key: 'taxRate', width: '4%', type: FormTypes.inputNumber,placeholder: '%'},
          { title: '税额', key: 'taxMoney', width: '5%', type: FormTypes.inputNumber, readonly: true, statistics: true },
          { title: '价税合计', key: 'taxLastMoney', width: '7%', type: FormTypes.inputNumber, statistics: true },
          { title: '备注', key: 'remark', width: '6%', type: FormTypes.input },
          { title: '关联id', key: 'linkId', width: '5%', type: FormTypes.hidden },
          { title: '是否再次编辑', key: 'isEdit', width: '5%', type: FormTypes.hidden },
        ]
      },
      confirmLoading: false,
      //校验
      validatorRules:{
        invoiceNumber:{
          rules: [
            { required: true, message: '请输入发票编号!' }
          ]
        },
        invoiceType:{
          rules: [
            { required: true, message: '请选择发票类型!' }
          ]
        },
        customerSupplierId:{
          rules: [
            { required: true, message: '请选择对应的客户/供应商!' }
          ]
        },
        invoiceAccount:{
          rules: [
            { required: true, message: '请选择相应的结算账户！' }
          ]
        },
      },
      //通用api调用地址
      url: {
        add: '/invoice/add',
        edit: '/depotHead/updateDepotHeadAndDetail',
        detailList: '/depotItem/getDetailList'
      }
    }
  },
  created () {
  },
  methods: {
    //1.单据查看详细信息
    myHandleDetail(record) {
      findBillDetailByNumber({ number: record.number }).then((res) => {
        if (res && res.code === 200) {
          let type = res.data.depotHeadType
          type = type.replace('其它','')
          this.$refs.billDetail.show(res.data, type)
          this.$refs.billDetail.title=type+"-详情"
        }
      })
    },
    //2.客户||供应商下拉框发生变动
    cliOrSupChange(val){
      let tagName = this.iceType===1?"销售":"采购";
      let organId = Number(val);
      let type = this.iceType===1?"出库":"入库";
      let search = {"type":type,"subType":tagName,"status":"1,2,3","organId":organId};
      getAction("/depotHead/list",{"search":search,"pageSize":"100","currentPage":"1"}).then(res=>{        
        if(res.data.rows.length<=0){
          this.$message.warning("当前客户没有需要开票的单据~");
          this.linkBillListOk([{}]);
          this.bill.data = [];
          return;
        }
        //过滤数据
        this.linkBillListOk([{}]);
        const thisData = res.data.rows.filter(item=>item.materialCount!=item.invoiceQuantity)
        if(thisData.length<=0){
          this.$message.warning("当前客户的单据已全部开票~");
        }
        this.bill.data = thisData;
      })
    },
    //3.发票类型发生变化
    invoiceTypeChange(val){
      //获取变化的值转成number
      this.iceType = Number(val);
      //滞空结算账户报关单号，详细数据，单据数据。
      this.form.setFieldsValue({"customerSupplierId":undefined,"reportNo":undefined,})
      this.detailData = [];
      this.bill.data = [];
    },
    //4.调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.billStatus = '0'
      this.currentSelectDepotId = ''
      this.rowCanEdit = true
      this.materialTable.columns[1].type = FormTypes.popupJsh
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'snList', 0)
      this.changeFormTypes(this.materialTable.columns, 'batchNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'expirationDate', 0)
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 0)
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
      } else {
        if(this.model.linkNumber) {
          this.rowCanEdit = false
          this.materialTable.columns[1].type = FormTypes.normal
        }
        this.model.operTime = this.model.operTimeStr
        this.model.debt = (this.model.discountLastMoney + this.model.otherMoney - this.model.changeAmount).toFixed(2)
        if(this.model.accountId == null) {
          this.model.accountId = 0
          this.manyAccountBtnStatus = true
          this.accountIdList = this.model.accountIdList
          this.accountMoneyList = this.model.accountMoneyList
        } else {
          this.manyAccountBtnStatus = false
        }
        this.fileList = this.model.fileName
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'invoiceNumber', 'invoiceType', 'invoiceDate', 'linkNumber', 'invoiceRemark',
            'discount','discountMoney','discountLastMoney','otherMoney','accountId','changeAmount','debt','deliveryNoteId'))
        });
        // 加载子表数据
        let params = {
          headerId: this.model.id,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList')),  //扩展属性
          linkType: 'basic'
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList;
        this.requestSubTableData(url, params, this.materialTable);
      }
      //复制新增单据-初始化单号和日期
      if(this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      //初始化数据（客户，供应商，仓库，结算账户）
      // this.initSystemConfig()
      this.initSupplier(0)
      this.initCustomer(0)
      this.initDepot()
      this.initAccount(0)
      // this.initPlatform()
      // this.initQuickBtn()
    },
    //5.提交单据时整理成formData
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      billMain.type = '其它'
      billMain.subType = '票据管理'
      for(let item of detailArr){
        totalPrice += item.allPrice-0
      }
      billMain.totalPrice = totalPrice
      if(billMain.accountId === 0) {
        billMain.accountId = ''
      }
      billMain.accountIdList = this.accountIdList.length>0 ? JSON.stringify(this.accountIdList) : ""
      billMain.accountMoneyList = this.accountMoneyList.length>0 ? JSON.stringify(this.accountMoneyList) : ""
      if(this.fileList && this.fileList.length > 0) {
        billMain.fileName = this.fileList
      } else {
        billMain.fileName = ''
      }
      if(this.model.id){
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      return {
        info: JSON.stringify(billMain),
        rows: JSON.stringify(detailArr),
      }
    },
    //6.赋值数据道详细表格中
    linkBillListOk(selectBillDetailRows, linkNumber, organId, discountMoney, deposit, remark) {
      discountMoney = 0; //这里我没用退款优惠金额 补个0
      this.rowCanEdit = false
      this.materialTable.columns[1].type = FormTypes.normal
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
      if(selectBillDetailRows && selectBillDetailRows.length>0) {
        let listEx = []
        let allTaxLastMoney = 0
        for(let j=0; j<selectBillDetailRows.length; j++) {
          let info = selectBillDetailRows[j];
          if(info.finishNumber>0) {
            info.operNumber = info.preNumber - info.finishNumber
            info.allPrice = info.operNumber * info.unitPrice-0
            let taxRate = info.taxRate-0
            info.taxMoney = (info.allPrice*taxRate/100).toFixed(2)-0
            info.taxLastMoney = (info.allPrice + info.taxMoney).toFixed(2)-0
          }
          info.linkId = info.id
          allTaxLastMoney += info.taxLastMoney
          listEx.push(info)
          this.changeColumnShow(info)
        }
        this.materialTable.dataSource = listEx
        ///给优惠后金额重新赋值
        allTaxLastMoney = allTaxLastMoney?allTaxLastMoney:0
        let discount = 0
        if(allTaxLastMoney!==0) {
          discount = (discountMoney/allTaxLastMoney*100).toFixed(2)-0
        }
        let discountLastMoney = (allTaxLastMoney - discountMoney).toFixed(2)-0    
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'organId': organId,
            'deliveryNoteId': linkNumber,
            'discount': discount,
            'discountMoney': discountMoney,
            'subtotal': allTaxLastMoney, //未税总金额
            'discountLastMoney': discountLastMoney,
            'changeAmount': discountLastMoney,
            'invoiceRemark': remark
          })
        })
      }
    },
  },
  computed: {
    //1.计算单据列表 返现详细信息
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          // 1. 得到当前选中的条目
          const selectedIds = new Set(selectedRows.map(item => item.id));
          // 2. 根据当前条目过滤数据，并创建一个 Set 来提高查找效率
          const existingIds = new Set(this.detailData.map(item => item.headerId));
          this.detailData = this.detailData.filter(item => selectedIds.has(item.headerId));
          // 3. 收集需要从数据库获取的 id
          const missingIds = [...selectedIds].filter(id => !existingIds.has(id));
          // 4. 查询赋值，使用 Promise.all 处理多个异步请求
          if (missingIds.length > 0) {
            const fetchPromises = missingIds.map(id => {
              const params = { headerId: id, mpList: '', linkType: 'basic' };
              return getAction("/depotItem/getDetailList", params).then(res => {
                if (res && res.data && Array.isArray(res.data.rows)) {
                  //修改rows的operNumber为0
                  const rows = res.data.rows;
                  rows.forEach(item=>{item.operNumber = 0;})
                  // 确保每次添加的数据都是新的对象，避免直接修改原始数据
                  const newItems = rows.map(item => ({ ...item }));
                  this.detailData.push(...newItems);
                  // 更新 existingIds 以包含新添加的 headerId
                  newItems.forEach(item => existingIds.add(item.headerId));
                }
              }).catch(error => {
                console.error("Error fetching data from database:", error);
              });
            });
            // 等待所有异步请求完成后再调用 linkBillListOk
            Promise.all(fetchPromises).then(() => {
              this.linkBillListOk(this.detailData,Array.from(selectedIds).join(','));
            }).catch(error => {
              console.error("One or more fetch operations failed:", error);
            });
          } else {
            // 如果没有需要查询的 id，直接调用 linkBillListOk
            this.linkBillListOk(this.detailData,Array.from(selectedIds).join(','));
          }
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
          },
        }),
      };
    },
  },
}
</script>
<style scoped>

</style>